const svg = d3.select('svg');

const width = +svg.attr('width');
const height = +svg.attr('height');

const render = data => {
  const xValue = d => d.population;
  const yValue = d => d.city;
  const margin = { top: 50, bottom: 20, left: 100, right: 20};
  const innerWidth = width - margin.left - margin.right;
  const innerHeight = height - margin.top - margin.bottom;
  
  const xScale = d3.scaleLinear()
    .domain([0, d3.max(data, xValue)])
	.range([0, innerWidth]);
  
  const yScale = d3.scaleBand()
    .domain(data.map(yValue))
	.range([0, innerHeight])
	.padding(0.2);//轴间距
  
  const g = svg.append('g')
    .attr('transform',`translate(${margin.left},${margin.bottom})`);
  
  const yAxis = d3.axisLeft(yScale);
  const yAxisGroup = g.append('g').call(yAxis);
  yAxisGroup.selectAll('.domain, .tick line')
	.remove();
  yAxisGroup.append('text')
    .attr('fill', 'black')
    .attr('x', 0)
	.attr('y', 0)
	.text('城市');
  
  //格式化x轴数据
  const xAxisFormat = number => number == 0 ? 0 : number/10000 + '万';
  const xAxis = d3.axisBottom(xScale)
    .tickFormat(xAxisFormat)
	//添加网格线
	.tickSize(-innerHeight);
 
  const xAxisGroup = g.append('g').call(xAxis)
    .attr('transform',`translate(0, ${innerHeight})`);
  //去除x轴轴线
  xAxisGroup.selectAll('.domain').remove();
  //添加x轴名称
  xAxisGroup.append('text')
    .attr('fill', 'black')
    .attr('y', 40)
	.attr('x', innerWidth/2)
	.text('人口（万）');
  
  g.selectAll('rect').data(data)
    .enter().append('rect')
      .attr('y', d => yScale(yValue(d)))
      .attr('width', d => xScale(xValue(d)))
      .attr('height', yScale.bandwidth());
	  
  g.append('text')
    .attr('y', -1)
	.attr('x',innerWidth/3)
	.text('中国人口最多的十个城市');
}

d3.csv('data.csv').then( data => {
  data.forEach(d => {
	d.population = +d.population * 10000;  
  });
  render(data);
});